﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// 对委托的扩展
/// </summary>
public static class DelegateExtend
{
    /// <summary>
    /// 遍历委托链，已try-catch，提供异常回调
    /// </summary>
    public static void InvokeForeach(this Delegate myDelegate, Action<Exception> exceptionCallback, params object[] args)
    {
        foreach (var item in myDelegate.GetInvocationList())
        {
            try
            {
                item?.DynamicInvoke(args);
            }
            catch (Exception e)
            {
                exceptionCallback?.Invoke(e);
            }
        }

    }

    public static void InvokeForeach<T>(this Action<T> action, Action<Exception> exceptionCallback, T arg)
    {
        foreach (Action<T> item in action.GetInvocationList())
        {
            try
            {
                item?.Invoke(arg);
            }
            catch (Exception e)
            {
                exceptionCallback?.Invoke(e);
            }
        }
    }


    /// <summary>
    /// 如果之前注册过了，则返回false，否则true
    /// </summary>
    public static bool Contains(this Action myDelegaet, Action d)
    {
        foreach (var item in myDelegaet.GetInvocationList())
        {
            if (item.Method == d.Method && item.Target == d.Target) return true;
        }

        return false;
    }
}
